import { motion } from 'framer-motion';
import { CameraOutlined, SwapOutlined, LoadingOutlined, PrinterOutlined, CameraFilled } from '@ant-design/icons';
import { useRef, useEffect, useState } from 'react';
import Webcam from 'react-webcam';
import styles from '../styles/index.module.css';
import { Template } from '../types';

interface CameraPreviewProps {
  selectedTemplate: Template | null;
  onCapture: (imageData: string) => void;
}

export const CameraPreview = ({ selectedTemplate, onCapture }: CameraPreviewProps) => {
  const webcamRef = useRef<Webcam>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isCapturing, setIsCapturing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [capturedImage, setCapturedImage] = useState<string | null>(null);
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);

  // 检查摄像头权限
  useEffect(() => {
    const checkCameraPermission = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        stream.getTracks().forEach(track => track.stop());
        setHasPermission(true);
      } catch (err) {
        setHasPermission(false);
        setError('无法访问相机');
      } finally {
        setIsLoading(false);
      }
    };

    checkCameraPermission();
  }, []);

  const handlePrint = async (imageData: string) => {
    try {
      // 创建打印窗口
      const printWindow = window.open('', '_blank');
      if (!printWindow) {
        throw new Error('无法打开打印窗口');
      }

      // 构建打印内容
      const printContent = `
        <!DOCTYPE html>
        <html>
          <head>
            <title>打印照片</title>
            <style>
              body {
                margin: 0;
                padding: 20px;
                display: flex;
                flex-direction: column;
                align-items: center;
                background: #f5f5f5;
              }
              .print-container {
                background: white;
                padding: 20px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                border-radius: 8px;
                max-width: 800px;
                width: 100%;
              }
              .photo {
                width: 100%;
                height: auto;
                border-radius: 4px;
                margin-bottom: 20px;
              }
              .template-info {
                text-align: center;
                color: #666;
                font-size: 14px;
                margin-top: 10px;
              }
              @media print {
                body {
                  background: white;
                  padding: 0;
                }
                .print-container {
                  box-shadow: none;
                  padding: 0;
                }
              }
            </style>
          </head>
          <body>
            <div class="print-container">
              <img src="${imageData}" class="photo" alt="拍摄的照片" />
              ${selectedTemplate ? `
                <div class="template-info">
                  <p>模板: ${selectedTemplate.name}</p>
                  <p>打印时间: ${new Date().toLocaleString()}</p>
                </div>
              ` : ''}
            </div>
            <script>
              window.onload = function() {
                setTimeout(() => {
                  window.print();
                  window.close();
                }, 500);
              }
            </script>
          </body>
        </html>
      `;

      // 写入打印内容
      printWindow.document.write(printContent);
      printWindow.document.close();
    } catch (err) {
      setError(err instanceof Error ? err.message : '打印失败');
    }
  };

  const handleCapture = async () => {
    try {
      if (!webcamRef.current) {
        throw new Error('相机未就绪');
      }

      setIsCapturing(true);
      const imageSrc = webcamRef.current.getScreenshot();
      
      if (!imageSrc) {
        throw new Error('获取照片失败');
      }

      // 保存捕获的图片
      setCapturedImage(imageSrc);
      
      // 模拟处理延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 调用打印功能
      await handlePrint(imageSrc);
      
      // 通知父组件
      onCapture(imageSrc);
    } catch (err) {
      setError(err instanceof Error ? err.message : '拍照失败');
    } finally {
      setIsCapturing(false);
    }
  };

  const handleVideoError = (error: string) => {
    setError(error);
    setIsLoading(false);
  };

  // 渲染相机预览或兜底内容
  const renderCameraContent = () => {
    if (hasPermission === false) {
      return (
        <div className="w-full h-full flex flex-col items-center justify-center bg-gray-100">
          <div className="text-center p-6">
            <div className="w-24 h-24 rounded-full bg-gray-200 flex items-center justify-center mb-4">
              <CameraFilled className="text-4xl text-gray-400" />
            </div>
            <h3 className="text-lg font-medium text-gray-800 mb-2">无法访问相机</h3>
            <p className="text-gray-600 mb-4">请允许访问相机以使用拍照功能</p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors"
            >
              重试
            </button>
          </div>
        </div>
      );
    }

    return (
      <Webcam
        ref={webcamRef}
        audio={false}
        screenshotFormat="image/jpeg"
        videoConstraints={{
          width: 1080,
          height: 1080,
          facingMode: 'user'
        }}
        onUserMedia={() => setIsLoading(false)}
        onUserMediaError={() => handleVideoError('无法访问相机')}
        className="w-full h-full object-cover"
      />
    );
  };

  return (
    <div className="relative w-full h-full overflow-hidden">
      {/* 相机预览区域 */}
      <div className="relative w-full h-full flex items-center justify-center">
        <div className="relative aspect-square w-full max-w-[100vh]">
          {renderCameraContent()}

          {/* 加载状态 */}
          {isLoading && hasPermission !== false && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/50">
              <div className="loading-spinner">
                <LoadingOutlined className="text-4xl text-white" />
              </div>
            </div>
          )}

          {/* 错误提示 */}
          {error && hasPermission !== false && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/50">
              <div className="text-white text-center p-4">
                <p className="text-lg font-medium mb-2">{error}</p>
                <p className="text-sm opacity-80">请检查相机权限设置</p>
              </div>
            </div>
          )}

          {/* 模板预览层 */}
          {selectedTemplate && !isLoading && !error && hasPermission !== false && (
            <div className="absolute inset-0">
              <img
                src={selectedTemplate.imageUrl}
                alt={selectedTemplate.name}
                className="w-full h-full object-cover opacity-30"
              />
              <div className="absolute bottom-0 left-0 right-0 p-4 glass-effect">
                <h3 className="text-white text-lg font-medium">{selectedTemplate.name}</h3>
              </div>
            </div>
          )}

          {/* 拍照按钮 */}
          {!isLoading && !error && hasPermission !== false && (
            <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2">
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={handleCapture}
                disabled={isCapturing}
                className={`px-8 py-3 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 shadow-lg flex items-center justify-center group ${
                  isCapturing ? 'opacity-75 cursor-not-allowed' : ''
                }`}
              >
                <div className="relative">
                  {/* 背景光效 */}
                  <div className="absolute inset-0 bg-white/20 blur-xl rounded-full animate-pulse"></div>
                  
                  {/* 文字内容 */}
                  <div className="relative flex items-center space-x-2">
                    {isCapturing ? (
                      <>
                        <LoadingOutlined className="text-xl text-white" />
                        <span className="text-white font-medium text-lg">处理中...</span>
                      </>
                    ) : (
                      <>
                        <PrinterOutlined className="text-xl text-white" />
                        <span className="text-white font-medium text-lg">拍照并打印</span>
                      </>
                    )}
                  </div>

                  {/* 装饰效果 */}
                  <div className="absolute -inset-1 bg-gradient-to-r from-blue-400/30 to-purple-500/30 rounded-full blur-md group-hover:blur-lg transition-all duration-300"></div>
                </div>
              </motion.button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}; 